#! /usr/bin/env bash

if [[ $EUID != 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

set -e
shopt -s nullglob

readonly mydir=${0%/*}
readonly datadir="${mydir}/data"

# these are just made up, it doesn't matter what they are for the test
readonly ip4="192.168.42.42"
readonly ip6="2001:0db8:85a3:0000:0000:8a2e:0370:7334"
readonly mac="01:23:45:67:89:ab"

# run a test given the pcap file path, the no. of packets expected to
# the output file, the no. packets for the reject file, and a firewall policy
function test-filter {
  local test_name=$1 n_accepted=$2 n_rejected=$3 n_dropped=$4 rule=$5
  output=`mktemp`
  echo "TEST $test_name"
  "${mydir}/../../../snabb" wall filter -p -4 $ip4 -6 $ip6 -m $mac -o `mktemp` -r `mktemp` -e "$rule" pcap "${datadir}/$test_name" > $output
  if ! (grep "Accepted packets: $n_accepted" $output &&
        grep "Rejected packets: $n_rejected" $output &&
        grep "Dropped packets:  $n_dropped" $output); then
      echo "FAIL"
      result=1
  else
      echo "SUCCESS"
      result=0
  fi
  rm $output
  return $result
}

# Reject all DHCPv6 packets and drop all the rest.
test-filter "dhcpv6.pcap" 0 6 4 "{ DHCPV6 = 'reject', default = 'drop' }"

# Reject all HTTP packets and accept all the test.
test-filter "v6-http.cap" 51 4 0 "{ HTTP = 'reject', default = 'accept' }"

# Accept RTP packets which flow_count is equals or higher than 69 and drop otherwise. Drop non RTP packets.
test-filter "rtp_example.pcap" 465 0 34 "{ RTP = [[match { flow_count >= 69 => accept; otherwise => drop }]], default = 'drop' }"

# Reject RTP packets which flow_count is equals or higher than 69 and drop otherwise. Drop non RTP packets.
test-filter "rtp_example.pcap" 0 465 34 "{ RTP = [[match { flow_count >= 69 => reject; otherwise => drop }]], default = 'drop' }"
